package com.example.demo2.service;

import com.example.demo2.bean.FragmentBean;
import com.example.demo2.dao.FragmentBeanDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FragmentBeanService {

    @Autowired
    FragmentBeanDao dao;

    public List<FragmentBean> list(){
        List<FragmentBean> all = dao.findAll();
        return all;
    }

    public FragmentBean login(FragmentBean yourBean) {
        FragmentBean yourBean1 = dao.findOne(Example.of(yourBean)).orElse(null);
        return yourBean1;
    }

//    点赞
    public FragmentBean setGoods(FragmentBean yourBean){
//        FragmentBean fragmentBeanOn = new FragmentBean();
        FragmentBean fragmentBean = dao.findOne(Example.of(new FragmentBean(yourBean.getFg_id()))).orElse(null);
        String[] arr = fragmentBean.getGood().split(",");
//        String asd = "a,s,d,f,g";
//        String[] arr = asd.split(",");
//        System.out.println(arr);
        int type = 0;
//        List<String> list = new ArrayList();
        StringBuffer goods = new StringBuffer();
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
            if (arr[i].equals(yourBean.getUser_id())){
                type = 1;
            }else {
//                list.add(arr[i]);
                if (goods.length() > 1) {
//                    String gd = "," + arr[i];
//                    goods.concat(gd);
                    goods.append(","+arr[i]);
                } else {
                    goods.append(arr[i]);
                }
            }
        }
        if (type==0){
//            点赞
//            list.add(yourBean.getUser_id());
            fragmentBean.setGood(fragmentBean.getGood()+","+yourBean.getUser_id());
        }else {
//            取消点赞
            fragmentBean.setGood(goods.toString());
        }
        FragmentBean save = dao.save(fragmentBean);
        return save;
    }

    public FragmentBean register(FragmentBean yourBean) {
        FragmentBean save = dao.save(yourBean);
        return save;
    }

    public FragmentBean findone(FragmentBean yourBean) {
        FragmentBean yourBean1 = dao.findOne(Example.of(yourBean)).orElse(null);
        return yourBean1;
    }

    public void deleteById(Integer id) {
        dao.deleteById(id);
    }

    public FragmentBean update(FragmentBean yourBean) {
        FragmentBean save = dao.save(yourBean);
        return save;
    }

    public FragmentBean addone(FragmentBean yourBean) {
        FragmentBean save = dao.save(yourBean);
        return save;
    }
}
